package com.hx.er.common.util;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class UserLoginCounterUtil {
	private static Map<String, Integer> userLoginMap = new HashMap<String, Integer>();
	private static Date originalDate;

	/**
	 * @param key
	 * @return
	 */
	public synchronized static int userLoginCount(String key) {
		if (originalDate == null) {
			originalDate = new Date();
		} else {
			// 获取原日期和当前日期的年、月、日
			Calendar cal = Calendar.getInstance();
			cal.setTime(originalDate);
			int originalYear = cal.get(Calendar.YEAR);
			int originalMonth = cal.get(Calendar.MONTH);
			int originalDateOfMonth = cal.get(Calendar.DAY_OF_MONTH);

			cal = Calendar.getInstance();
			int newYear = cal.get(Calendar.YEAR);
			int newMonth = cal.get(Calendar.MONTH);
			int newDateOfMonth = cal.get(Calendar.DAY_OF_MONTH);

			// 如果日期已经变化，原来保存的全部信息全部刷新
			if (originalYear != newYear || originalMonth != newMonth || originalDateOfMonth != newDateOfMonth) {
				userLoginMap.clear();
				originalDate = cal.getTime();
			}
		}

		// 判断是否已经存在该用户记录
		if (!userLoginMap.containsKey(key)) {
			userLoginMap.put(key, 1);
			return 1;
		} else {
			int newCount = userLoginMap.get(key) + 1;
			userLoginMap.put(key, newCount);
			return newCount;
		}
	}

	public static int getUserLoginCount(String key) {
		if (!userLoginMap.containsKey(key)) {
			return 0;
		} else {
			return userLoginMap.get(key);
		}
	}
}
